/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles.plugins;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.Toast;
import de.drak.Profiles.OnlineHelp;
import de.drak.Profiles.R;
import de.drak.Profiles.TimedProfiles;

/**Used to Edit a Screen Setting
 * - Control Brightness
 * - Control Timeout
 * */
public class ScreenSeter extends Activity {

	private static final int MENU_SAVE = 1;
	private static final int MENU_DONT_SAVE = 2;
	static final String SAVE_TIME = "screen.time";
	static final String SAVE_BRIGHT = "screen.bright";
	private static final int MINIMUM_BACKLIGHT = 18;//less will set screen off!
	private static final int MAXIMUM_BACKLIGHT = 255;
	private static final int NO_TIMEOUT = -1;
	
	private int currBrightness;
	private int currTime;

	/**Indicates if Activity should return RESULT_CANCELED*/
	private boolean isCancelled;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		
		setContentView(R.layout.set_screen);

        //load title
		TimedProfiles.createTitle(this, getString(R.string.plugin_screenset));
	
		SeekBar bar = (SeekBar) findViewById(R.id.SeekBar01);
		SeekBar barT = (SeekBar) findViewById(R.id.SeekBar02);
		bar.setMax(MAXIMUM_BACKLIGHT - MINIMUM_BACKLIGHT);
		barT.setMax(600000);
		bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				updateWindowBrightness();
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				//not needed
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				//not needed
			}
		});
		final Activity my_akt = this;
		barT.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				//not needed
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				//not needed
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				Toast.makeText(my_akt, getTimeOutText(seekBar.getProgress()), Toast.LENGTH_SHORT).show();
			}
		});		
		

		currBrightness = Settings.System.getInt(this.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 0);
		int val = currBrightness - MINIMUM_BACKLIGHT;
		bar.setProgress(val);
		bar.setSecondaryProgress(val);
		
		currTime = Settings.System.getInt(this.getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0);
		val = currTime==NO_TIMEOUT?0:currTime;
		barT.setProgress(val);
		barT.setSecondaryProgress(val);

		/*
		 * if savedInstanceState == null, then we are entering the Activity directly and we need to check whether the
		 * Intent has forwarded a Bundle extra (e.g. whether we editing an old condition or creating a new one)
		 */
		if (savedInstanceState == null)
		{
			final Bundle forwardedBundle = getIntent().getBundleExtra(QueryReceiver.INTENT_BUNDLE);

			/*
			 * the forwardedBundle would be null if this was a new condition
			 */
			if (forwardedBundle == null)
			{
				//current bar level is set above
				
				((CheckBox) findViewById(R.id.CheckBox03)).setChecked(true);
				((CheckBox) findViewById(R.id.CheckBox03)).setVisibility(View.VISIBLE);
			}else{
				if(getIntent().hasExtra(TimedProfiles.INTENT_BUNDLE_UNSET))
				{
					//there is an unset bundle
					((CheckBox) findViewById(R.id.CheckBox03)).setVisibility(View.VISIBLE);
					((CheckBox) findViewById(R.id.CheckBox03)).setText(R.string.unsetbundle_edit);
				}
				
				if(forwardedBundle.containsKey(SAVE_BRIGHT))
				{
					((CheckBox) findViewById(R.id.CheckBox01)).setChecked(true);
					bar.setProgress(forwardedBundle.getInt(SAVE_BRIGHT) - MINIMUM_BACKLIGHT);
				}
				if(forwardedBundle.containsKey(SAVE_TIME))
				{
					((CheckBox) findViewById(R.id.CheckBox02)).setChecked(true);
					barT.setProgress(forwardedBundle.getInt(SAVE_TIME));
				}

			}
		}
		/*
		 * if savedInstanceState != null, there is no need to restore any Activity state directly (e.g. onSaveInstanceState()).
		 * This is handled by the Spinner automatically
		 */
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void finish()
	{
		if (isCancelled)
			setResult(RESULT_CANCELED);
		else
		{

			/*
			 * This is the return Intent, into which we'll put all the required extras
			 */
			final Intent returnIntent = new Intent();

			/*
			 * This extra is the data to ourselves: either for the Activity or the BroadcastReceiver. Note that anything placed in
			 * this Bundle must be available to Locale's class loader. So storing String, int, and other basic objects will work
			 * just fine. You cannot store an object that only exists in your app, as Locale will be unable to serialize it.
			 */
			final Bundle storeAndForwardExtras = new Bundle();

			boolean some_to_save = false;
			StringBuilder statstr = new StringBuilder();
			
			if(((CheckBox) findViewById(R.id.CheckBox01)).isChecked())
			{
				//charging
				some_to_save = true;
				
				final int p = ((SeekBar) findViewById(R.id.SeekBar01)).getProgress() +  MINIMUM_BACKLIGHT;
				
				statstr.append(String.format("Hell: %d", p));
				
				storeAndForwardExtras.putInt(SAVE_BRIGHT, p);
			}
			if(((CheckBox) findViewById(R.id.CheckBox02)).isChecked())
			{
				//less then
				final int p = ((SeekBar) findViewById(R.id.SeekBar02)).getProgress();
				
				some_to_save = true;
				statstr.append(String.format("Time: %s", getTimeOutText(p)));
				
				storeAndForwardExtras.putInt(SAVE_TIME, p==0?NO_TIMEOUT:p);
			}
			if(!some_to_save){
				//nothing
				setResult(TimedProfiles.RESULT_REMOVE);
				super.finish();
				return;
			}
			
			returnIntent.putExtra(TimedProfiles.INTENT_INFO_STR, statstr.toString());
			storeAndForwardExtras.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_SCREEN);
			returnIntent.putExtra(QueryReceiver.INTENT_BUNDLE, storeAndForwardExtras);
			
			if(((CheckBox) findViewById(R.id.CheckBox03)).getVisibility()==View.VISIBLE
					&& ((CheckBox) findViewById(R.id.CheckBox03)).isChecked())
			{
				//new instance - unset bundle
				final Bundle endB = new Bundle(),
							caps  = new Bundle();
				if(((CheckBox) findViewById(R.id.CheckBox01)).isChecked())
				{
					endB.putInt(SAVE_BRIGHT, currBrightness);
				}
				if(((CheckBox) findViewById(R.id.CheckBox02)).isChecked())
				{
					endB.putInt(SAVE_TIME, currTime);
				}
				endB.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_SCREEN);
				
				caps.putString(TimedProfiles.INTENT_INFO_STR, "!"+statstr.toString());
				caps.putBundle(QueryReceiver.INTENT_BUNDLE, endB);
				
				returnIntent.putExtra(TimedProfiles.INTENT_BUNDLE_UNSET, caps);
			}

			setResult(RESULT_OK, returnIntent);
		}

		super.finish();
	}
	private String getTimeOutText(int s)
	{
		if(s==0)
		{
			return "never";
		}
		int m=0;
		while(s>60000)
		{
			s-=60000;
			++m;
		}
		return String.format("after %d:%d", m,s/1000);
	}
	

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);

		final Intent helpIntent = new Intent(this, OnlineHelp.class);
		helpIntent.putExtra("com.twofortyfouram.locale.intent.extra.HELP_URL", OnlineHelp.HELP_URL_PRE+"plugin/ScreenSeter");

		// Note: title set in onCreate
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle());

		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);
		menu.add(0, MENU_DONT_SAVE, 0, android.R.string.cancel)
			.setIcon(android.R.drawable.ic_menu_close_clear_cancel).getItemId();
		menu.add(0, MENU_SAVE, 0, R.string.plugin_save)
			.setIcon(android.R.drawable.ic_menu_save).getItemId();
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_SAVE:
			{
				finish();
				return true;
			}
			case MENU_DONT_SAVE:
			{
				isCancelled = true;
				finish();
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}

	private void updateWindowBrightness() {
		
		// update window brightness with a delay of 300 ms
		Handler handler = new Handler();
		
		//final Activity mActivity = this;
		
		handler.postAtTime(new Runnable(){
			public void run() {
								
				int value = ((SeekBar) findViewById(R.id.SeekBar01)).getProgress() + MINIMUM_BACKLIGHT;
				
				// update current view's brightness
				LayoutParams attrs = getWindow().getAttributes();
				attrs.screenBrightness = value / 255f;
				
				// request brightness update
				Window window = getWindow();
				window.setAttributes(attrs);
			}
		}, SystemClock.uptimeMillis() + 300);
		
	}
}